﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Uber.Storage;
using Uber.Collections;

namespace Uber.HabboHotel.Rooms.Chatlogs
{
    class ChatlogsManager
    {
        private SafeList<ChatMessage> Chatlogs;

        public ChatlogsManager()
        {
            this.Chatlogs = new SafeList<ChatMessage>();
        }

        public void AddChatlog(uint Id, uint RoomId, int Hour, int Minute, double UnixTimeStamp, string Message, string Username, string LongDateTime)
        {
            Chatlogs.Add(new ChatMessage(Id, RoomId, Hour, Minute, UnixTimeStamp, Message, Username, LongDateTime));
        }

        public void Save()
        {
            this.SaveChatlogs();
        }

        public void PurgeChatlogs()
        {
            double Time = (UberEnvironment.GetUnixTimestamp() - 345600);

            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {
                dbClient.AddParamWithValue("timestamp", Time);
                dbClient.ExecuteQuery("DELETE FROM chatlogs WHERE timestamp <= @timestamp");
            }
        }

        private void SaveChatlogs()
        {
            if (Chatlogs.Count > 0)
            {
                foreach (ChatMessage Message in Chatlogs)
                {
                    using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
                    {
                        dbClient.AddParamWithValue("message", Message.Message);
                        dbClient.ExecuteQuery("INSERT INTO chatlogs (user_id,room_id,hour,minute,timestamp,message,user_name,full_date) VALUES ('" + Message.Id + "','" + Message.RoomId + "','" + Message.Hour + "','" + Message.Minute + "','" + Message.UnixTimeStamp + "',@message,'" + Message.Username + "','" + Message.LongDateTime + "')");
                    }
                }
            }

            this.Chatlogs = null;
            this.Chatlogs = new SafeList<ChatMessage>();
        }

        public List<ChatMessage> GetChatLogs(uint RoomId)
        {
            var Messages = new List<ChatMessage>();

            foreach (ChatMessage Message in Chatlogs)
            {
                if (Message.RoomId == RoomId)
                {
                    Messages.Add(Message);
                }
            }

            return Messages.ToList();
        }
    }
}
